from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos.cos_exception import CosServiceError
import sys
import logging
from django.conf import settings
from sts.sts import Sts

secret_id = settings.TENCENT_COS_ID
secret_key = settings.TENCENT_COS_KEY


def create_bucket(bucket, region='ap-chengdu'):
    """
    创建桶
    :param bucket: 桶名称
    :param region: 区域
    :return:
    """

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 创建桶
    client.create_bucket(
        Bucket=bucket,
        ACL='public-read',  # private/ public-read/ public-read-write
    )

    # 解决跨域问题
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'POST', 'PUT', 'HEAD', 'DELETE'],
                'AllowedHeader': '*',
                'ExposeHeader': '*',
                'MaxAgeSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config,
    )


def upload_file(bucket, region, file_obj, key, ):
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 上传文件
    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=file_obj,  # 本地文件路径
        Key=key,  # 上传到桶后的文件名
    )

    # https://bug-manager-1314200773.cos.ap-chengdu.myqcloud.com/p1.jpg
    return "https://{}.cos.{}.myqcloud.com/{}".format(bucket, region, key)


def delete_file(bucket, region, key, ):
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 删除文件
    client.delete_object(
        Bucket=bucket,
        Key=key,  # 上传到桶后的文件名
    )


def delete_file_list(bucket, region, key_list):
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 批量删除文件
    """
    objects = {
        "Quiet": "true",
        "Object": [
            {
                "Key": "file_name1"
            },
            {
                "Key": "file_name2"
            }
        ]
    }
    """
    objects = {
        "Quiet": "true",
        "Object": key_list,
    }

    client.delete_objects(
        Bucket=bucket,
        Delete=objects,  # 上传到桶后的文件名
    )


def credential(bucket, region):
    """ 获取 cos 上传的临时凭证 """
    # 生成一个临时凭证，并给前端返回

    config = {
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': secret_id,
        # 固定密钥 key
        'secret_key': secret_key,
        # 桶名称
        'bucket': bucket,
        # bucket 所在的地区
        'region': region,
        # 允许的路径前缀
        # 例如: a.jpg  或者 a/* 或者 * (使用 * 存在重大安全风险，谨慎使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限查看文档
        # https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            "name/cos:PutObject",
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # 'name/cos:UploadPart',
            # 'name/cos:UploadPartCopy',
            # 'name/cos:CompleteMultipartUpload',
            # 'name/cos:AbortMultipartUpload',
            # '*',
        ]
    }

    sts = Sts(config)
    result_dict = sts.get_credential()
    return result_dict


def check_file(bucket, region, key):
    """检查文件是否合法"""

    region = 'ap-chengdu'

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 检验上传的文件
    response = client.head_object(
        Bucket='13534907270-1666341907-1314200773',
        Key=key,
    )

    return response


def delete_bucket(bucket, region):
    """ 删除桶 """
    # 删除桶中的文件
    # 删除桶中的碎片
    # 删除空桶

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    try:
        # 找到所有桶中的所有文件
        while True:
            part_objs = client.list_objects(bucket)

            '''
            {'Name': '13534907270-1666341907-1314200773',
            'EncodingType': 'url',
            'Prefix': None,
            'Marker': None,
            'MaxKeys': '1000',
            'IsTruncated': 'false',
            'Contents': [
                {'Key': '1666402419913_python学习.png',
                 'LastModified': '2022-10-22T01:33:40.000Z',
                 'ETag': '"80bd0e87ef4decbbf09eccc85d0d9af5"',
                 'Size': '484716',
                 'Owner': {'ID': '1314200773', 'DisplayName': '1314200773'}, 'StorageClass': 'STANDARD'}],
            '''

            contents = part_objs.get('Contents')
            if not contents:
                break

            # 批量删除
            objects = {
                'Quiet': 'true',
                'Object': [{'Key': item['Key']} for item in contents]
            }

            client.delete_objects(Bucket=bucket, Delete=objects)

            if part_objs['IsTruncated'] == 'false':
                break

        # 找到碎片
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])

            if part_uploads['IsTruncated'] == 'false':
                break
        # 删除桶
        client.delete_bucket(bucket)
    except CosServiceError as e:
        pass
